package com.bwie.service.impl;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.http.server.HttpServerRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.mapper.TbUserMapper;
import com.bwie.state.CheckEnum;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
* @author HP
* @description 针对表【tb_user(用户表)】的数据库操作Service实现
* @createDate 2025-04-21 15:54:51
*/
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
    implements TbUserService{
    @Autowired
    TbUserMapper userMapper;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    HttpServletRequest request;
    @Autowired
    FastFileStorageClient fastFileStorageClient;
    @Override
    public R pageList(PageInfoVo pageInfoVo) {
        Page<TbUser> page = new Page<>(pageInfoVo.getPageNum(),pageInfoVo.getPageSize());
        LambdaQueryWrapper<TbUser> wrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNoneEmpty(pageInfoVo.getKeyWord())){
            wrapper.like(TbUser::getUserName,pageInfoVo.getKeyWord()).or()
                    .like(TbUser::getNickName,pageInfoVo.getKeyWord()).or()
                    .like(TbUser::getUserMobile,pageInfoVo.getKeyWord()).or()
                    .like(TbUser::getUserEmail,pageInfoVo.getKeyWord());
        }
        Page<TbUser> pageList = userMapper.selectPage(page, wrapper);
        return R.OK(pageList);
     }

    @Override
    public R login(TbUser user) {
        LambdaQueryWrapper<TbUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbUser::getUserName,user.getUserName());
        TbUser loginUser = userMapper.selectOne(wrapper);
        if(loginUser==null){
            return R.ERROR(404,"用户不存在");
        }
        if(!loginUser.getUserPass().equals(user.getUserPass())){
            return R.ERROR(500,"密码错误");
        }
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie").claim("userId", loginUser.getUserId()).compact();
        String tokenKey="token"+loginUser.getUserId();
        redisTemplate.opsForValue().set(tokenKey,token,60, TimeUnit.MINUTES);
        loginUser.setUserPass(null);
        loginUser.setToken(token);
        return R.OK(loginUser);
    }

    @Override
    public R addUser(TbUser user) {
        LambdaQueryWrapper<TbUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbUser::getUserName,user.getUserName());
        TbUser user1 = userMapper.selectOne(wrapper);
        if(user1!=null){
            return R.ERROR(404,"账户存在,不可重复添加");
        }
        user.setCreateTime(new Date());
        userMapper.insert(user);
        return R.OK();
    }

    @Override
    public R checkUser(TbUser user) {
        TbUser checkUser = userMapper.selectById(user.getUserId());
        if(checkUser==null){
            return R.ERROR(404,"用户不存在");
        }
        if(user.getUserStatus().equals(CheckEnum.CHECK_NO.getCode())){
            //审核驳回
            if(user.getReasons()==null){
                return R.ERROR(500,"请填写审核原因");
            }
        }
        checkUser.setUserStatus(user.getUserStatus());
        checkUser.setReasons(user.getReasons());
        userMapper.updateById(user);
        return R.OK();
    }

    @Override
    public R getMyInfo() {
        String token = request.getHeader("token");
        if(token==null){
            return R.ERROR(404,"token不存在,请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
        TbUser user = userMapper.selectById(userId);
        return R.OK(user);
    }

    @Override
    public R updateUser(TbUser user) {
        TbUser updateUser = userMapper.selectById(user.getUserId());
        if(updateUser==null){
            return R.ERROR(404,"用户不存在");
        }
        userMapper.updateById(user);
        return R.OK();
    }

    @Override
    public R updloadFile(MultipartFile file) {
        try {
            String extName = FileNameUtil.extName(file.getOriginalFilename());
            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extName, null);
            String url = "http://192.168.41.192:8888/"+storePath.getFullPath();
            return R.OK(url);
        } catch (IOException e) {
            e.printStackTrace();
            return R.ERROR(500,"上传失败");
        }

    }

    @Override
    public R deleteByUserId(Integer userId) {
        TbUser user = userMapper.selectById(userId);
        if(user==null){
            return R.ERROR(404,"用户不存在,删除失败!");
        }
        userMapper.deleteById(userId);
        return R.OK();
    }
}




